#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from Utils.Logger import Logger, now_date
from Utils.PropertiesParsor import ParsePageProperty
from Config.GlobalVariables import *
import shutil
import os

logger = Logger().get_logger()
parser = ParsePageProperty()
backup_date_path = os.path.join(BACKUP_PATH, now_date)
backup_logs_path = os.path.join(backup_date_path, "Logs")
backup_reports_path = os.path.join(backup_date_path, "Reports")
backup_screenshots_path = os.path.join(backup_date_path, "Screenshots")
backup_searchresults_path = os.path.join(backup_date_path, "SearchResults")


def init_backup_folders():
    logger.info("Initialize Backup and inner Folders")
    if not os.path.exists(BACKUP_PATH):
        logger.debug("Backup Folder is not existed, create new one")
        os.mkdir(BACKUP_PATH)
    if not os.path.exists(backup_date_path):
        logger.debug("Backup Date Folder is not existed, create new one")
        os.mkdir(backup_date_path)
    if not os.path.exists(backup_logs_path):
        logger.debug("Backup Logs Folder is not existed, create new one")
        os.mkdir(backup_logs_path)
    if not os.path.exists(backup_screenshots_path):
        logger.debug("Backup Screenshots Folder is not existed, create new one")
        os.mkdir(backup_screenshots_path)
    if not os.path.exists(backup_searchresults_path):
        logger.debug("Backup SearchResults Folder is not existed, create new one")
        os.mkdir(backup_searchresults_path)


def init_results_folders():
    logger.info("Initialize Results and inner Folders")
    if not os.path.exists(RESULTS_PATH):
        logger.debug("Results Folder is not existed, create new one")
        os.mkdir(RESULTS_PATH)
    if not os.path.exists(RESULTS_LOGS_PATH):
        logger.debug("Results Logs Folder is not existed, create new one")
        os.mkdir(RESULTS_LOGS_PATH)
    if not os.path.exists(RESULTS_SCREENSHOTS_PATH):
        logger.debug("Results Screenshots Folder is not existed, create new one")
        os.mkdir(RESULTS_SCREENSHOTS_PATH)
    if not os.path.exists(RESULTS_SEARCHRESULTS_PATH):
        logger.debug("Results SearchResults Folder is not existed, create new one")
        os.mkdir(RESULTS_SEARCHRESULTS_PATH)


def backup_results(file_type, results_folder_path, target_folder_path):
    logger.info("Backup {0}".format(results_folder_path))
    for root, dirs, files in os.walk(results_folder_path):
        for file in files:
            if file.split(".")[1] == file_type:
                file_path = os.path.join(results_folder_path, file)
                target_path = os.path.join(target_folder_path, file)
                # 如果有相同文件则覆盖
                if os.path.exists(target_path):
                    os.remove(target_path)
                logger.debug("Copy {0}".format(file))
                shutil.copy(file_path, target_path)
    logger.debug("Finish backup and remove {0}".format(results_folder_path))
    shutil.rmtree(results_folder_path, ignore_errors=True)


def init_page_cookies():
    logger.info("Initialize Page Cookies Of Page Property")
    key_path_list = parser.get_property_path("cookies")
    for key_path in key_path_list:
        parser.set_property_value(key_path, [])


def initialize():
    try:
        init_backup_folders()
        if os.path.exists(RESULTS_LOGS_PATH):
            backup_results("log", RESULTS_LOGS_PATH, backup_logs_path)
        if os.path.exists(RESULTS_SCREENSHOTS_PATH):
            backup_results("png", RESULTS_SCREENSHOTS_PATH, backup_screenshots_path)
        if os.path.exists(RESULTS_SEARCHRESULTS_PATH):
            backup_results("json", RESULTS_SEARCHRESULTS_PATH, backup_searchresults_path)
        init_results_folders()
        init_page_cookies()
    except Exception as e:
        logger.error("Fail to initialze: {0}".format(str(e)))
        raise e

if __name__ == "__main__":
    initialize()
